package bank;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class BankServer {
	private ServerSocket serverSocket;
	private Socket socket;
	private ObjectInputStream ois, oisFile;
	private ObjectOutputStream oos, oosFile;
	private FileInputStream fis;
	private FileOutputStream fos;
	
	public BankServer(){
		try {
			serverSocket = new ServerSocket(7897);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	
	public void start(){
		try {
			socket = serverSocket.accept();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		
		HashMap<String, AccountModel> list = null;
		try {
			ois = new ObjectInputStream(socket.getInputStream());
			list = (HashMap<String, AccountModel>)ois.readObject();
			if(list==null){
				fis = new FileInputStream("account.dat");
				oisFile = new ObjectInputStream(fis);
				list = (HashMap<String, AccountModel>)oisFile.readObject();
				
				oos = new ObjectOutputStream(socket.getOutputStream());
				oos.writeObject(list);
			}else if(list!=null){
				fos = new FileOutputStream("account.dat");
				oosFile = new ObjectOutputStream(fos);
				oosFile.writeObject(list);
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
		} catch (ClassNotFoundException e) {
			System.out.println(e.getMessage());
		}
	}
	
	public void createFile(){
		File f = new File("account.dat");
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				System.out.println("file : " + e.getMessage());
			}
		}
	}
	
	public static void main(String a[]){
		BankServer bs = new BankServer();
		while(true){
			bs.start();
		}
	}
}
